home *** CD-ROM | disk | FTP | other *** search
/ Magnum One / Magnum One (Mid-American Digital) (Disc Manufacturing).iso / d12 / cpptutor.arc / CHAP07.TXT < prev    next >
Text File  |  1991-04-28  |  20KB  |  474 lines

  1.  
  2.  
  3.  
  4.                                                         Chapter 7
  5.                                                       INHERITANCE
  6.  
  7. One reason to use inheritance is that it allows you to reuse code
  8. from a previous project but gives you the flexibility to slightly
  9. modify it if the old code doesn't do exactly what you need for the
  10. new project.  It doesn't make sense to start every new project from
  11. scratch since some code will certainly be repeated in several
  12. programs and you should strive to build on what you did previously. 
  13. Another reason for using inheritance is if the project requires the
  14. use of several classes which are very similar but slightly
  15. different.
  16.  
  17. In this chapter we will concentrate on the mechanism of inheritance
  18. and how to build it into a program.  A better illustration of why
  19. you would use inheritance will be given in later chapters where we
  20. will discuss some practical applications of object oriented
  21. programming.
  22.  
  23. The principle of inheritance is available with several modern
  24. programming languages and is handled slightly differently with
  25. each.  C++ allows you to inherit all or part of the methods of a
  26. class, modify some, and add new ones not available in the parent
  27. class.  You have complete flexibility, and as usual, the method
  28. used with C++ has been selected to result in the most efficient
  29. code execution.
  30.  
  31.  
  32. A SIMPLE CLASS TO START WITH
  33. _________________________________________________________________
  34.  
  35. Examine the file named VEHICLE.HPP for a simple   ===============
  36. class which we will use to begin our study of       VEHICLE.HPP
  37. inheritance in this chapter.  There is nothing    ===============
  38. unusual about this class header, it has been
  39. kept very simple.  It consists of four simple
  40. methods which can be used to manipulate data pertaining to our
  41. vehicle.  What each method does is not especially important at this
  42. time.  We will eventually refer to this as a superclass but for the
  43. time being, we will simply use it like any other class to show that
  44. it is indeed identical to the classes already studied.
  45.  
  46. Ignore lines 4, 5, and 17 until the end of this chapter where they
  47. will be explained in detail.  This file cannot be compiled or
  48. executed because it is only a header file.
  49.  
  50.  
  51.  
  52. THE IMPLEMENTATION FOR VEHICLE
  53. _________________________________________________________________
  54.  
  55. Examine the file named VEHICLE.CPP and you will find that it is the
  56. implementation of the vehicle class.  The initialize() method
  57.  
  58.                                                          Page 7-1
  59.  
  60.                                           Chapter 7 - Inheritance
  61.  
  62. assigns the values input as parameters to the     ===============
  63. wheels and weight variables.  We have methods to    VEHICLE.CPP
  64. return the number of wheels and the weight, and   ===============
  65. finally, we have one that does a trivial
  66. calculation to return the loading on each wheel. 
  67. We will have a few examples of methods that do some significant
  68. processing later, but at this point, we are more interested in
  69. learning how to set up the interface to the classes, so the
  70. implementations will be kept trivial.
  71.  
  72. As stated above, this is a very simple class which will be used in
  73. the next program.  Later in this tutorial we will use it as a
  74. superclass.  You should compile this class at this time in
  75. preparation for the next example program, but you cannot execute
  76. it because there is no entry point.
  77.  
  78.  
  79.  
  80. USING THE VEHICLE CLASS
  81. _________________________________________________________________
  82.  
  83. The file named TRANSPRT.CPP uses the vehicle     ================
  84. class in exactly the same manner as we             TRANSPRT.CPP
  85. illustrated in the last chapter.  This should be ================
  86. an indication to you that this is truly nothing
  87. more than a normal class as defined in C++.  We
  88. will make it a little special, however, by using it unmodified as
  89. a superclass in the next few example files to illustrate
  90. inheritance.  Inheritance uses an existing class and adds
  91. functionality to it to accomplish another, possibly more complex
  92. job.
  93.  
  94. You should have no problem understanding the operation of this
  95. program.  It declares four objects of the vehicle class,
  96. initializes them, and prints out a few of the data points to
  97. illustrate that the vehicle class can be used as a simple class
  98. because it is a simple class.  We are referring to it as a simple
  99. class as opposed to calling it a superclass or subclass as we will
  100. do shortly.
  101.  
  102. If you thoroughly understand this program, you should compile and
  103. execute it, remembering to link the vehicle object file with this
  104. object file.
  105.  
  106.  
  107.  
  108. OUR FIRST SUBCLASS
  109. _________________________________________________________________
  110.  
  111. Examine the file named CAR.HPP for our first      ===============
  112. example of the use of a subclass.  The vehicle        CAR.HPP
  113. class is inherited due to the ": public vehicle"  ===============
  114. added to line 4.  This class named car is
  115. composed of all of the information included in
  116.  
  117.                                                          Page 7-2
  118.  
  119.                                           Chapter 7 - Inheritance
  120.  
  121. the superclass vehicle, and all of its own additional information. 
  122. Even though we did nothing to the class named vehicle, we made it
  123. into a superclass because of the way we are using it here.  To go
  124. a step further, even though it will be used as a superclass in an
  125. example program later in this chapter, there is no reason it cannot
  126. continue to be used as a simple class in the previous example
  127. program.  In fact, it can be used as a single class and a
  128. superclass in the same program.  The question of whether it is a
  129. simple class or a super class is answered by the way it is used.
  130.  
  131. A discussion of terminology is needed here.  When discussing object
  132. oriented programming in general, a class that inherits another is
  133. called a subclass, but the proper term as defined for C++ is a
  134. derived class.  Since both terms are very descriptive, and most
  135. writers tend to use the terms interchangeably, we will also use
  136. both terms in this tutorial.
  137.  
  138. A superclass is a rather general class which can cover a wide range
  139. of objects, whereas a subclass is somewhat more restricted but at
  140. the same time more useful.  For example if we had a superclass
  141. named programming language and a subclass named C++, then we could
  142. use the superclass to define Pascal, Ada, C++, or any other
  143. programming language, but it would not tell us about the use of
  144. classes in C++ because it can only give a general view of each
  145. language.  On the other hand, the subclass named C++ could define
  146. the use of classes, but it could not be used to describe the other
  147. languages because it is too narrow.  A superclass tends to be more
  148. general, and a subclass is more specific.
  149.  
  150. In this case, the vehicle superclass can be used to declare objects
  151. that represent trucks, cars, bicycles, or any number of other
  152. vehicles you can think up.  The class named car however can only
  153. be used to declare an object that is of type car because we have
  154. limited the kinds of data that can be intelligently used with it. 
  155. The car class is therefore more restrictive and specific than the
  156. vehicle class.  The vehicle class is more general than the car
  157. class.
  158.  
  159. If we wished to get even more specific, we could define a subclass
  160. of car and name it sports_car and include such information as
  161. red_line_limit for the tachometer which would be silly for the
  162. family station wagon.  The car class would therefore be used as a
  163. subclass and a superclass at the same time, so it should be clear
  164. that these names refer to how a class is used.
  165.  
  166.  
  167.  
  168. HOW DO WE DECLARE A SUBCLASS?
  169. _________________________________________________________________
  170.  
  171. Enough generalities about classes, let's get down to the specifics. 
  172. A subclass is defined by including the header file for the
  173. superclass as is done in line 2, then the name of the superclass
  174. is given following the name of the subclass separated by a colon
  175.  
  176.                                                          Page 7-3
  177.  
  178.                                           Chapter 7 - Inheritance
  179.  
  180. as is illustrated in line 4.  Ignore the keyword public immediately
  181. following the colon in this line.  It is optional and we will study
  182. it in detail in the next chapter.  All objects declared as being
  183. of class car therefore are composed of the two variables from the
  184. class vehicle because they inherit those variables, and the single
  185. variable declared in the class car named passenger_load.
  186.  
  187. An object of this class will have three of the four methods of
  188. vehicle and the two new ones declared here.  The method named
  189. initialize() which is part of the vehicle class will not be
  190. available here because it is hidden by the local version of
  191. initialize() which is a part of the car class.  The local method
  192. will be used if the name is repeated allowing you to customize your
  193. new class.
  194.  
  195. Note once again that the implementation for the superclass only
  196. needs to be supplied in its compiled form.  The source code for the
  197. implementation can be hidden for economic reasons to aid software
  198. developers.  Hiding the source code also allows the practice of
  199. information hiding.  The header for the superclass must be
  200. available as a text file since the class definitions are required
  201. in order to use the class.
  202.  
  203.  
  204.  
  205. THE CAR CLASS IMPLEMENTATION
  206. _________________________________________________________________
  207.  
  208. Examine the file named CAR.CPP which is the       ===============
  209. implementation file for the car class.  The           CAR.CPP
  210. first thing you should notice is that this file   ===============
  211. has no indication of the fact that it is a
  212. subclass of any other file, that can only be
  213. determined by inspecting the header file for the class.  Since we
  214. can't tell if it is a subclass or not, it is written in exactly the
  215. same way as any other class implementation file.
  216.  
  217. Line 8 contains a new construct.  In order to initialize the
  218. variables which are a part of the superclass, we must send a
  219. message to the superclass.  This is because the variables are
  220. private and directly available only within the class itself.  We
  221. will see another way to do this in the next chapter of this
  222. tutorial.
  223.  
  224. If you think you understand this file, you should compile it for
  225. later use.  Keep in mind that you must have already compiled the
  226. vehicle class prior to this time in order to get a good compilation
  227. of this subclass.
  228.  
  229.  
  230.  
  231.  
  232.  
  233.  
  234.  
  235.  
  236.                                                          Page 7-4
  237.  
  238.                                           Chapter 7 - Inheritance
  239.  
  240. ANOTHER SUBCLASS
  241. _________________________________________________________________
  242.  
  243. Examine the file named TRUCK.HPP for an example   ===============
  244. of another class that uses the vehicle class and     TRUCK.HPP
  245. adds to it.  Of course, it adds different things  ===============
  246. to it because it will specialize in those things
  247. that pertain to trucks.  In fact it adds two
  248. more variables and three methods.  Once again, ignore the keyword
  249. public following the colon in line 4 for a few minutes and we will
  250. cover it in detail in the next chapter of this tutorial.
  251.  
  252. A very important point that must be made is that the car class and
  253. the truck class have absolutely nothing to do with each other, they
  254. only happen to be subclasses of the same superclass or parent class
  255. as it is sometimes called.
  256.  
  257. Note that both the car and the truck classes have methods named
  258. passengers() but this causes no problems and is perfectly
  259. acceptable.  If classes are related in some way, and they certainly
  260. are if they are both derived classes of a common superclass, you
  261. would expect them to be doing somewhat similar things.  In this
  262. situation there is a good possibility that a method name would be
  263. repeated in both subclasses.
  264.  
  265.  
  266.  
  267. THE TRUCK IMPLEMENTATION
  268. _________________________________________________________________
  269.  
  270. Examine the file named TRUCK.CPP for the          ===============
  271. implementation of the truck class.  It also has      TRUCK.CPP
  272. a few unusual things included in it.  In line 13  ===============
  273. of the second method, it uses a call to its
  274. superclass to get the weight of the truck.  This
  275. is because the weight is private and therefore not available to
  276. the subclass but must be accessed via one of the superclass
  277. methods.  There is a way to make it available here, but we will
  278. save that definition until the next chapter of this tutorial.
  279.  
  280. You should have no problem understanding the remainder of this
  281. program.  Your assignment at this point is to compile it in
  282. preparation for our example program that uses all three of the
  283. classes defined in this chapter.
  284.  
  285.  
  286. USING ALL THREE CLASSES
  287. _________________________________________________________________
  288.  
  289. Examine the example program named ALLVEHIC.CPP   ================
  290. for an example that uses all three of the          ALLVEHIC.CPP
  291. classes we have been discussing in this chapter. ================
  292. It uses the superclass vehicle to declare
  293. objects and also uses the two subclasses to
  294.  
  295.                                                          Page 7-5
  296.  
  297.                                           Chapter 7 - Inheritance
  298.  
  299. declare objects.  This was done to illustrate that all three
  300. classes can be used in a single program.
  301.  
  302. All three of the header files for the classes are included in lines
  303. 3 through 5 so the program can use the components of the classes. 
  304. Notice that the implementations of the three classes are not in
  305. view here and do not need to be in view.  This allows the code to
  306. be used without access to the source code for the actual
  307. implementation of the class.  However, it should be clear that the
  308. header file definition must be available.
  309.  
  310. In this example program, only one object of each class is declared
  311. and used but as many as desired could be declared and used in order
  312. to accomplish the programming task at hand.  You will notice how
  313. clean and uncluttered the source code is for this program since the
  314. classes were developed, debugged, and stored away previously, and
  315. the interfaces were kept very simple.  There is nothing new here
  316. so you should have no trouble understanding the operation of this
  317. program.
  318.  
  319. Compiling and executing this program will take a bit of effort but
  320. the process is not complicated.  The three classes and the main
  321. program can be compiled in any order desired.  All four must be
  322. compiled prior to linking the four resulting object (or binary)
  323. files together prior to any attempt to execute the final program. 
  324. Be sure you do the required steps to compile and execute this
  325. program because the effective use of C++ will require you to
  326. compile many separate files and link them together.  This is
  327. because of the nature of the C++ language, but it should not be a
  328. burden if a good "make" capability exists with your compiler.
  329.  
  330.  
  331.  
  332. WHY THE #ifndef VEHICLEHPP ?
  333. _________________________________________________________________
  334.  
  335. We promised to return to the strange looking preprocessor directive
  336. in lines 4, 5 and 17 in the VEHICLE.HPP file, and this is the time
  337. for it.  When we define the subclass car, we are required to supply
  338. it with the full definition of the interface to the vehicle class
  339. since car is a subclass of vehicle and must know all about its
  340. parent.  We do that by including the vehicle class into the car
  341. class, and the car class can be compiled.  The vehicle class must
  342. also be included in the header file of the truck class for the same
  343. reason.
  344.  
  345. When we get to the main program, we must inform it of the details
  346. of all three classes, so all three header files must be included
  347. as is done in lines 3 through 5 of ALLVEHIC.CPP, but this leads to
  348. a problem.  When the preprocessor gets to the car class, it
  349. includes the vehicle class because it is listed in the car class
  350. header file, but since the vehicle class was already included in
  351. line 3 of ALLVEHIC.CPP, it is included twice and we attempt to
  352. redefine the class vehicle.  Of course it is the same definition,
  353.  
  354.                                                          Page 7-6
  355.  
  356.                                           Chapter 7 - Inheritance
  357.  
  358. but the system doesn't care, it simply doesn't allow redefinition
  359. of a class.  We allow the double inclusion of the file and at the
  360. same time prevent the double inclusion of the class by building a
  361. bridge around it using the word VEHICLEHPP.  If the word is already
  362. defined, the definition is skipped, but if the word is not defined,
  363. the definition is included and the word is defined at that time. 
  364. The end result is the actual inclusion of the class only once even
  365. though the file is included more than once.  You should have no
  366. trouble understanding the logic of the includes if you spend a
  367. little time studying this program sequence.
  368.  
  369. Even though ANSI-C allows multiple definitions of entities,
  370. provided the definitions are identical, C++ does not permit this. 
  371. The primary reason is because the compiler would have great
  372. difficulty in knowing if it has already made a constructor call for
  373. the redefined entity, if there is one.  A multiple constructor call
  374. for a single object could cause great havoc, so C++ was defined to
  375. prevent any multiple constructor calls by making it illegal to
  376. redefine any entity.  This is not a problem in any practical
  377. program.
  378.  
  379. The name VEHICLEHPP was chosen as the word because it is the name
  380. of the file, with the period omitted.  If the name of the file is
  381. used systematically in all of your class definitions, you cannot
  382. have a name clash because the filename of every class must be
  383. unique.  It would be good for you to get into the practice of
  384. building the optional skip around all of your classes.
  385.  
  386.  
  387.  
  388. MULTIPLE INHERITANCE
  389. _________________________________________________________________
  390.  
  391. Early implementations of C++ do not allow multiple inheritance,
  392. inheriting data and methods from more than one parent class.  The
  393. newest versions of C++ permit multiple inheritance since the latest
  394. definition of the language (AT&T version 2.0 of C++), includes it
  395. as a part of its syntax.  One of the biggest problems with multiple
  396. inheritance is the question of what should be done when both parent
  397. classes have methods of the same name.  Some means must be
  398. available to decide which of the methods will actually be
  399. inherited.
  400.  
  401. Chapter 9 of this tutorial will discuss multiple inheritance.
  402.  
  403.  
  404.  
  405.  
  406.  
  407.  
  408.  
  409.  
  410.  
  411.  
  412.  
  413.  
  414.                                                          Page 7-7
  415.  
  416.                                           Chapter 7 - Inheritance
  417.  
  418. PROGRAMMING EXERCISES
  419. _________________________________________________________________
  420.  
  421.  
  422. 1.   Add another object of the vehicle class to ALLVEHIC.CPP named
  423.      bicycle, and do some of the same operations as were done to
  424.      the unicycle.  You will only need to recompile the main
  425.      program and link all four files together to get an executable
  426.      file, the three classes will not require recompilation.
  427.  
  428. 2.   Add the optional skip around the header files of the classes
  429.      named car and truck.  Then recompile all four files and relink
  430.      them to get an executable file.
  431.  
  432. 3.   Add a new method to the truck class to return the total weight
  433.      of the truck plus its payload and add code to ALLVEHIC.CPP to
  434.      read the value out and display it on the monitor.  This will
  435.      require an addition to TRUCK.HPP, another addition to
  436.      TRUCK.CPP, and of course the changes to the main program named
  437.      ALLVEHIC.CPP.  The answer is given as three files named
  438.      CH07_3A.HPP (TRUCK.HPP), CH07_3B.CPP (TRUCK.CPP) and the
  439.      changed main program is found in CH07_3C.CPP in the answer
  440.      directory on the distribution disk for this tutorial.
  441.  
  442.  
  443.  
  444.  
  445.  
  446.  
  447.  
  448.  
  449.  
  450.  
  451.  
  452.  
  453.  
  454.  
  455.  
  456.  
  457.  
  458.  
  459.  
  460.  
  461.  
  462.  
  463.  
  464.  
  465.  
  466.  
  467.  
  468.  
  469.  
  470.  
  471.  
  472.  
  473.                                                          Page 7-8
  474.